import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class StatusButton extends StatefulWidget {
  final Widget none;
  final Function(ButtonStatusController) stateController;
  final Widget loading;
  final Widget done;
  final Function onPressed;
  final ButtonStyle style;

  StatusButton({
    Key key,
    @required this.none,
    this.stateController,
    this.loading,
    this.done,
    this.onPressed,
    this.style,
  })  : assert(none != null),
        super(key: key);

  @override
  _StatusButtonState createState() => _StatusButtonState();
}

enum ButtonStatus { none, loading, done }

class ButtonStatusController extends Cubit<ButtonStatus> {
  ButtonStatusController({ButtonStatus value = ButtonStatus.none}) : super(value);

  set value(ButtonStatus value) {
    emit(value);
  }
}

class _StatusButtonState extends State<StatusButton> {
  ButtonStatusController _cubit = ButtonStatusController();

  @override
  void initState() {
    super.initState();
    widget.stateController?.call(_cubit);
  }

  @override
  Widget build(BuildContext context) {
    Widget indicator = Platform.isIOS ? CupertinoActivityIndicator() : CircularProgressIndicator(backgroundColor: Colors.white, strokeWidth: 2);
    return BlocProvider.value(
      value: _cubit,
      child: BlocBuilder<ButtonStatusController, ButtonStatus>(
        builder: (context, data) {
          Widget child;
          switch (data) {
            case ButtonStatus.loading:
              child = widget.loading == null ? indicator : widget.loading;
              break;
            case ButtonStatus.done:
              child = widget.done == null ? Text('请求成功') : widget.done;
              break;
            case ButtonStatus.none:
            default:
              child = widget.none;
              break;
          }
          return ElevatedButton(
            child: child,
            onPressed: widget.onPressed == null ? _onPressed : widget.onPressed,
            style: widget.style,
          );
        },
      ),
    );
  }

  void _onPressed() {
    if (_cubit.state != ButtonStatus.none) {
      return;
    }
    _cubit.value = ButtonStatus.loading;
  }
}
